<?
  // ob_start("ob_gzhandler");

  require_once('../db.php');
  require_once('../util/misc.php');
  require_once('../util/JSON.php');
  db_connect();
  $json = new Services_JSON();

  function clusterize($points, $clid) {
    $c = array();
    $num = count($points);
    $c["id"] = $clid;
    $c["type"] = 2;
    $c["num"] = $num;
    $avglat = 0.0;
    $avglng = 0.0;
    for ($i=0; $i<$num; $i++) {
      $avglat += $points[$i]["lat"];
      $avglng += $points[$i]["lng"];
    }
    $avglat /= $num;
    $avglng /= $num;
    $c["lat"] = $avglat;
    $c["lng"] = $avglng;
    return $c;
  }

  function wgs_to_mappos($lng, $lat, $z) {
    $shift = $z + 7;
    $mp = array();

    $x = intval(($lng/180.0 + 1.0) * (1<<$shift));
    $mp["x"] = $x & ((1<<($z+8))-1);

    $sinf = sin(deg2rad(-$lat));
    $y = log((1.0+$sinf)/(1.0-$sinf)) / (M_PI*2)+1;
    $mp["y"] = intval($y * (1<<$shift));

    return $mp;
  }

  $build_clusters = true;

  $bboxs = $_GET["bbox"];
  $w = intval($_GET["w"]);
  $h = intval($_GET["h"]);
  $z = intval($_GET["z"]);
  $bbox = false;
  if ($z > 5 && !empty($bboxs)) {
    $bbox = split(',', $bboxs, 4);
    for ($i=0; $i<4; $i++)
      $bbox[$i] = doubleval($bbox[$i]);
  }

  // results
  $r = array();

  $query = 'SELECT id_TPT AS id, unix_timestamp(date_time_TPT) AS tm, longitude_TPT AS lng, latitude_TPT AS lat, test_tpt AS test';
  $query .= ', description_TPT as descr, user_TPT AS uid, username AS un, name AS fn';
  $query .= ', length_TPT as length, width_TPT as width, height_TPT as height, dispersed_TPT as isdisp, bag_eq_TPT as bageq';
  $query .= ', photo1_TPT as photo1, photo2_TPT as photo2, exclude_TPT as excluded, cleaned_tpt as cleaned';
  $query .= ', bad_road_TPT as dif, bad_road_rain_TPT as difr';
  $query .= ', perc_non_reciclable_TPT as perc0, perc_glass_TPT as perc1, perc_metal_TPT as perc2, perc_plastic_TPT as perc3';
  $query .= ', perc_paper_TPT as perc4, perc_rubber_TPT as perc5, perc_big_volume_TPT as perc6, perc_construction_TPT as perc7';
  $query .= ', verified_tpt as ver';
  $query .= ' FROM v_tpt_non_ver';
  if ($bbox)
    $query .= " WHERE Intersects(location_TPT, GeomFromText('POLYGON((".
              $bbox[0]." ".$bbox[1].",".$bbox[2]." ".$bbox[1].",".$bbox[2]." ".$bbox[3].",".$bbox[0]." ".$bbox[3].",".$bbox[0]." ".$bbox[1].
              "))'))";
  // $query .= ' ORDER BY id_TPT';
  $result = mysql_query($query) or die("ERROR PERFORMING QUERY '".$query."': ".mysql_error());

  $dx = ($w>>5)+1;
  $dy = ($h>>5)+1;
  $mp_start = wgs_to_mappos($bbox[0], $bbox[3], $z);
  $clusters = array();

  for ($i=0; $i<$dx; $i++)
    for ($j=0; $j<$dy; $j++)
      $clusters[] = array();

  while ($row = mysql_fetch_assoc($result)) {
    $a["id"] = intval($row["id"]);
    $a["type"] = 1;
    $a["lat"] = doubleval($row["lat"]);
    $a["lng"] = doubleval($row["lng"]);
    $a["tm"] = intval($row["tm"]);
    $a["uid"] = intval($row["uid"]);
    $a["dl"] = doubleval($row["length"]);
    $a["dw"] = doubleval($row["width"]);
    $a["dh"] = doubleval($row["height"]);
    if ($row["isdisp"] === 'Y') {
      $a["disp"] = true;
      if (!is_null($row["bageq"]))
        $a["bageq"] = doubleval($row["bageq"]);
      else
        $a["bageq"] = ($row["length"]*$row["width"]*$row["height"])*10/3;
    }
    else {
      $a["disp"] = false;
      $a["bageq"] = ($row["length"]*$row["width"]*$row["height"])*10/3;
    }
    if ($row["dif"] === 'Y')
      $a["dif"] = true;
    else
      $a["dif"] = false;
    if ($row["difr"] === 'Y')
      $a["difr"] = true;
    else
      $a["difr"] = false;

    $a["perc"] = array();
    for ($i=0; $i<8; $i++)
      $a["perc"][$i] = intval($row["perc".$i]);

    $a["ph"] = array();
    if (!is_null($row["photo1"]))
      $a["ph"][] = $row["photo1"];
    if (!is_null($row["photo2"]))
      $a["ph"][] = $row["photo2"];

    if (!is_null($row["excluded"]) && $row["excluded"] !== 'N' && strlen($row["excluded"]) !== 0)
      $ic = 1; // excluded
    elseif ($row["cleaned"] === 'Y')
      $ic = 2; // cleaned
    elseif ($row["ver"] !== 'Y')
      $ic = 3; // non-verified
    else
      $ic = 0; // non-cleaned
    $a["ic"] = $ic;
    $a["un"] = $row["un"];
    $a["fn"] = $row["fn"];
    $a["desc"] = $row["descr"];
    if ($build_clusters && $bbox) {
      $mp = wgs_to_mappos($a["lng"], $a["lat"], $z);
      $cx = ($mp["x"]-$mp_start["x"])>>5;
      $cy = ($mp["y"]-$mp_start["y"])>>5;
      if ($cx >= 0 && $cy >= 0 && $cx < $dx && $cy < $dy)
        $clusters[$cx*$dy+$cy][] = $a;
    }
    else
      $r[] = $a;
  }

  mysql_free_result($result);

  if ($build_clusters && $bbox) {
    $clusterid = 1000000;
    for ($i=0; $i<$dx; $i++)
      for ($j=0; $j<$dy; $j++) {
        $cnt = count($clusters[$i*$dy+$j]);
        // need to clusterize
        if ($cnt > 1)
          $r[] = clusterize($clusters[$i*$dy+$j], $clusterid++);
        // add to single results
        elseif ($cnt == 1)
          $r[] = $clusters[$i*$dy+$j][0];
      }
  }
/*
  // collection bases

  $query = 'SELECT id_fls AS id, unix_timestamp(time_date_fls) AS tm, longitude_fls AS lng, latitude_fls AS lat';
  $query .= ', name_fls AS name, description_fls as descr';
  $query .= ' FROM ldi_flagstation_fls ORDER BY id_fls';
  $result = mysql_query($query) or die("ERROR PERFORMING QUERY '".$query."': ".mysql_error());

  while ($row = mysql_fetch_assoc($result)) {
    $a = array();
    $a["id"] = intval($row["id"]);
    $a["type"] = 3;
    $a["lat"] = doubleval($row["lat"]);
    $a["lng"] = doubleval($row["lng"]);
    $a["tm"] = intval($row["tm"]);
    $a["name"] = $row["name"];
    $a["desc"] = $row["descr"];
    $a["ic"] = 4;
    $r[] = $a;
  }

  mysql_free_result($result);
*/
  echo $json->encode($r);
?>
